package com.jspgou.cms.action.front;

import static com.jspgou.cms.Constants.MEMBER_SYS;
import static com.jspgou.cms.Constants.STORE_SYS;
import static com.jspgou.core.web.Constants.BACK_URL;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.jspgou.cms.entity.Address;
import com.jspgou.cms.entity.Cart;
import com.jspgou.cms.entity.CartItem;
import com.jspgou.cms.entity.ShopYushou;
import com.jspgou.cms.entity.Order;
import com.jspgou.cms.entity.OrderItem;
import com.jspgou.cms.entity.Payment;
import com.jspgou.cms.entity.Product;
import com.jspgou.cms.entity.ProductFashion;
import com.jspgou.cms.entity.Shipping;
import com.jspgou.cms.entity.ShopMember;
import com.jspgou.cms.entity.ShopMemberAddress;
import com.jspgou.cms.entity.Store;
import com.jspgou.cms.manager.AddressMng;
import com.jspgou.cms.manager.CartItemMng;
import com.jspgou.cms.manager.CartMng;
import com.jspgou.cms.manager.ShopYushouMng;
import com.jspgou.cms.manager.OrderMng;
import com.jspgou.cms.manager.PaymentMng;
import com.jspgou.cms.manager.ProductFashionMng;
import com.jspgou.cms.manager.ProductMng;
import com.jspgou.cms.manager.ShippingMng;
import com.jspgou.cms.manager.ShopMemberAddressMng;
import com.jspgou.cms.manager.StoreMng;
import com.jspgou.cms.service.ShoppingSvc;
import com.jspgou.cms.web.CmsUtils;
import com.jspgou.cms.web.ShopFrontHelper;
import com.jspgou.cms.web.SiteUtils;
import com.jspgou.common.web.ResponseUtils;
import com.jspgou.common.web.springmvc.MessageResolver;
import com.jspgou.core.entity.Website;

@Controller
public class YushouAct {
	private static final Logger log = LoggerFactory
			.getLogger(YushouAct.class);
	//我的购物车
	private static final String SHOPPING_CART = "tpl.shoppingCart";
	private static final String CHECKOUT_SHIPPING = "tpl.checkoutYushou";
	private static final String MY_RETURN_ORDER = "tpl.myyushouOrder";
	/**
     * 预售订单列表页
     */
	public static final String TPL_YUSHOUORDER_LIST="tpl.yushouOrderList";
	public static final String TPL_YUSHOUORDER_VIEW="tpl.yushouOrderView";
	public static final String TPL_MYYUSHOU_VIEW="tpl.myYushouView";
	/**
	 * 确认预售订单
	 */
	private static final String SURE_ORDER="tpl.sureYushouOrder";
	private static final String TPL_YUSHOUSUCCESS="tpl.yushouSuccess";
	
	//选择收货地址、付款方式、配送方式
	@RequestMapping(value = "/yushou/checkout_yushou.jspx")
	public String shippingInput(Long productid,Integer count,HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		Website web = SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		if(member==null){
			return "redirect:../login.jspx";
		}
		
		//会员地址
		List<ShopMemberAddress> smalist = shopMemberAddressMng.getList(member.getId());
		model.addAttribute("smalist", smalist);
		//所处省份
		List<Address> plist=addressMng.getListById(null);
		model.addAttribute("plist", plist);
		model.addAttribute("count", count);
		//付款方式
		List<Payment> paylist=paymentMng.getList((long)1, true);
		model.addAttribute("paylist", paylist);
		Product product=productMng.findById(productid);
		
		Store store=product.getStore();
		Long storeId=null;
		if (store!=null) {
			storeId=store.getId();
		}
		StringBuffer str = new StringBuffer();
		String itemStr = str.toString();
		model.addAttribute("itemStr", itemStr);
		//配送方式
		List<Shipping> splist=shippingMng.getList(web.getId(),storeId,null, true);
		model.addAttribute("splist", splist);
		List<CartItem> clist=cartItemMng.findByStore(storeId,member.getId());
		model.addAttribute("clist", clist);
		model.addAttribute("store", store);
		model.addAttribute("product", product);
		ShopFrontHelper.setCommonData(request, model, web);
		return web.getTplSys(MEMBER_SYS, MessageResolver.getMessage(request,
				CHECKOUT_SHIPPING), request);
	}
	

	@RequestMapping(value = "/yushou/clearCart.jspx")
	public void clearCart(HttpServletRequest request, HttpServletResponse response,
			ModelMap model) throws JSONException{
		ShopMember member=CmsUtils.getMember(request);
		JSONObject json=new JSONObject();
		if(member == null){
			json.put("status", 0);
		}
		shoppingSvc.clearCart(member);
		json.put("status", 1);
		json.put("success", "成功");
		ResponseUtils.renderJson(response, json.toString());
	}
	
	
	//生成订单
	@RequestMapping(value = "/yushou/order_shipping.jspx", method = RequestMethod.POST)
	public String orderShipping(Long productid,Long count,Long deliveryMethodSelector,Long storeId,
			Long payment,Long deliveryInfo,Float totalFee,HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		Website web = SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		if(member==null){
			return "redirect:../login.jspx";
		}
		Product product=productMng.findById(productid);
		ShopMemberAddress shopMemberAddress=shopMemberAddressMng.findById(deliveryInfo);
		ShopYushou yushou=new ShopYushou();
		if(payment!=null){
			Payment pay=paymentMng.findById(payment);
			if (pay!=null) {
				yushou.setPay(pay);
			}
		}
		double weight=0;
		Date date=new Date();
		Long data=date.getTime()+member.getId();
		yushou.setCode(data.toString()+"00");
		yushou.setAddress(shopMemberAddress);
		yushou.setCreatedate(new Date());
		yushou.setUser(member);
		yushou.setProductid(product);
		yushou.setCount(count);
		yushou.setAmount(yushou.getProductid().getDingjin()*yushou.getCount());
		yushou.setYstatus((short)0);
		Shipping shipping=getShippingById(deliveryMethodSelector, storeId);
		weight=weight+product.getWeight()*count;	
		double freight=shipping.calPrice((double)weight);
		yushou.setWeight((double)weight);
		yushou.setFreight(freight);
		yushou.setShipid(shipping);
		mng.save(yushou);
		model.addAttribute("order", yushou);
		ShopFrontHelper.setCommonData(request, model, web);
		return web.getTplSys(MEMBER_SYS, MessageResolver.getMessage(request,SURE_ORDER), request);
	}
	
	public Shipping getShippingById(Long dr,Long storeId){
		Shipping shipping = null;
		if(storeId==null){
			if(shippingMng.findById(dr).getStore()==null){
				shipping=shippingMng.findById(dr);
			}
		}else{
			if(shippingMng.findById(dr).getStore()!=null){
				if(shippingMng.findById(dr).getStore().getId()==storeId){
					shipping=shippingMng.findById(dr);
				}
			}
		}
		return shipping;
	}
	
	// 计算运费
	@RequestMapping(value = "/yushou/ajaxtotalDelivery.jspx")
	public void ajaxtotalDelivery(Long deliveryMethod,Long storeId,String itemStr,
			HttpServletRequest request, HttpServletResponse response,ModelMap model) throws JSONException {
		ShopMember member=CmsUtils.getMember(request);
		JSONObject json=new JSONObject();
		if (member == null) {
			json.put("status", 0);
		}
		Shipping shipping=shippingMng.findById(deliveryMethod);
		//计算运费
		Double weight = getcartWeight(storeId,itemStr);
		Double freight=shipping.calPrice(weight);
		json.put("status", 1);
		json.put("freight", freight);
		ResponseUtils.renderJson(response, json.toString());
	}
		
	public 	Double getcartWeight(Long storeId,String itemStr){
		Double cartWeight = 0.0;
		List<CartItem> clist = new ArrayList<CartItem>();
		if(!StringUtils.isBlank(itemStr)){
			if(storeId!=null){
				if(cartItemMng.findById(Long.parseLong(itemStr)).getStore()!=null){
					if(cartItemMng.findById(Long.parseLong(itemStr)).getStore().getId()==storeId){
						clist.add(cartItemMng.findById(Long.parseLong(itemStr)));
					}
				}
			}else{
				if(cartItemMng.findById(Long.parseLong(itemStr)).getStore()==null){
					clist.add(cartItemMng.findById(Long.parseLong(itemStr)));
				}
			}
		}
		for(CartItem item:clist){
			cartWeight = (double) (item.getProduct().getWeight()*item.getCount());
		}
		return cartWeight;
	}

	//会员中心，我的预售订单
	@RequestMapping(value = "/yushou/myorder*.jspx", method = RequestMethod.GET)
	public String myyushouorder(String cl,Long productid,Long count,Long deliveryMethodSelector,
			Long payment,Long deliveryInfo,Float totalFee,HttpServletRequest request,
			HttpServletResponse response, ModelMap model) {
		Website web = SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		if(member==null){
			return "redirect:../login.jspx";
		}
		model.addAttribute("historyProductIds", "");
		model.addAttribute("cl",cl);
		Cookie[] cookie = request.getCookies();
		for (int i = 0; i < cookie.length; i++) {
			if (cookie[i].getName().equals("shop_record")) {
				String str = cookie[i].getValue();
				model.addAttribute("historyProductIds", str);
				break;
			}
		}
		List<Shipping> shippingList = shippingMng.getList(web.getId(),null,null, true);
		List<Payment> paymentList = paymentMng.getList(web.getId(), true);
		model.addAttribute("paymentList", paymentList);
		model.addAttribute("member", member);
		ShopFrontHelper.setCommonData(request, model, web);
		ShopFrontHelper.frontPageData(request, model);
		return web.getTplSys(MEMBER_SYS, MessageResolver.getMessage(request,MY_RETURN_ORDER), request);
		}
	
	//店铺预售订单列表
	@RequestMapping(value="/yushou/yushouOrderList.jspx")
	public String yushouOrder(String cl,Integer pageNo,HttpServletRequest request,ModelMap model){
		Website web=SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		if(member==null){
			return "redirect:../login.jspx";
		}
		Store store=member.getStore();
		model.addAttribute("cl", cl);
		model.addAttribute("store", store);
		model.addAttribute("member", member);
		model.addAttribute("pageNo", pageNo);
		ShopFrontHelper.setCommonData(request, model, web);
		ShopFrontHelper.frontPageData(request, model);
		return web.getTplSys(STORE_SYS, MessageResolver.getMessage(request,TPL_YUSHOUORDER_LIST), request);
	}
	
	//店铺预售订单详情
	@RequestMapping(value="/yushou/yushouOrderView.jspx")
	public String yushouOrderView(String cl,Long yushouId,Integer pageNo,HttpServletRequest request,ModelMap model){
		Website web=SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		if(member==null){
			return "redirect:../login.jspx";
		}
		Store store=member.getStore();
		ShopYushou yushou=mng.findById(yushouId);
		model.addAttribute("yushou", yushou);
		model.addAttribute("cl", cl);
		model.addAttribute("store", store);
		model.addAttribute("member", member);
		model.addAttribute("pageNo", pageNo);
		ShopFrontHelper.setCommonData(request, model, web);
		ShopFrontHelper.frontPageData(request, model);
		return web.getTplSys(STORE_SYS, MessageResolver.getMessage(request,TPL_YUSHOUORDER_VIEW), request);
	}
	
	//会员中心我的预售订单详情
	@RequestMapping(value="/yushou/myYushouView.jspx")
	public String myYushouOrderView(String cl,Long yushouId,Integer pageNo,HttpServletRequest request,ModelMap model){
		Website web=SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		if(member==null){
			return "redirect:../login.jspx";
		}
		ShopYushou yushou=mng.findById(yushouId);
		model.addAttribute("yushou", yushou);
		model.addAttribute("cl", cl);
		model.addAttribute("member", member);
		model.addAttribute("pageNo", pageNo);
		ShopFrontHelper.setCommonData(request, model, web);
		ShopFrontHelper.frontPageData(request, model);
		return web.getTplSys(MEMBER_SYS, MessageResolver.getMessage(request,TPL_MYYUSHOU_VIEW), request);
	}
	
	//会员查看卖家进度
	@RequestMapping(value="/yushou/viewYushouYes.jspx")
	public String viewYushouYes(String cl,String yuCode,Integer pageNo,HttpServletRequest request,ModelMap model){
		Website web=SiteUtils.getWeb(request);
		ShopMember member=CmsUtils.getMember(request);
		if(member==null){
			return "redirect:../login.jspx";
		}
		Order order=orderMng.findByCode(yuCode);
		model.addAttribute("member", member);
		model.addAttribute("order", order);
		model.addAttribute("pageNo", pageNo);
		ShopFrontHelper.setCommonData(request, model, web);
		ShopFrontHelper.frontPageData(request, model);
		return web.getTplSys(MEMBER_SYS, MessageResolver.getMessage(request,TPL_YUSHOUSUCCESS), request);
	}
	
	//店铺预售订单删除
	@RequestMapping(value="/yushou/storedelete.jspx")
	public String storedelete(Long[] yushouId,String cl,HttpServletRequest request,HttpServletResponse response,ModelMap model,Integer pageNo){
		ShopYushou[] beans;
		try{
			beans=mng.deleteByIds(yushouId);
			JSONObject json=new JSONObject();
			json.put("success", true);
			ResponseUtils.renderJson(response, json.toString());
			for(ShopYushou bean :beans){
				log.info("delete ShopYushou id={}",bean.getId());
			}
		}catch(Exception e){}
		model.addAttribute("pageNo", pageNo);
		model.addAttribute("cl", cl);
		return "redirect:yushouOrderList.jspx";
	}
	
	//会员中心预售订单删除
	@RequestMapping(value="/yushou/memberdelete.jspx")
	public String memberdelete(Long[] yushouId,String cl,HttpServletRequest request,HttpServletResponse response,ModelMap model,Integer pageNo){
		ShopYushou[] beans;
		try{
			beans=mng.deleteByIds(yushouId);
			for(ShopYushou bean :beans){
				log.info("delete ShopYushou id={}",bean.getId());
			}
		}catch(Exception e){}
		model.addAttribute("pageNo", pageNo);
		model.addAttribute("cl", cl);
		return "redirect:myorder.jspx";
	}
		
	@Autowired
	private ShopYushouMng mng;
	@Autowired
	private ShoppingSvc shoppingSvc;
	@Autowired
	private ProductMng productMng;
	@Autowired
	private ProductFashionMng productFashionMng;
	@Autowired
	private CartItemMng cartItemMng;
	@Autowired
	private CartMng cartMng;
	@Autowired
	private StoreMng storeMng;
	@Autowired
	private AddressMng addressMng;
	@Autowired
	private PaymentMng paymentMng;
	@Autowired
	private ShippingMng shippingMng;
	@Autowired
	private ShopMemberAddressMng shopMemberAddressMng;
	@Autowired
	private OrderMng orderMng;
}
